package com.carambatv.android.service;

import java.io.InputStream;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;

import com.carambatv.android.utils.ChannelProcessor;
import com.carambatv.android.utils.Config;
import com.carambatv.android.utils.HttpConnector;

/**
 * DataUpdateService - manages connection to server, retrieves data from it,
 * parses the response and updates database with new values in background
 * thread.
 */
public class UpdateChannelService extends IntentService {

	private static final String TAG = UpdateChannelService.class.getSimpleName();

	public static final String EXTRA_STATUS_RECEIVER = "extra_receiver";
	public static final String EXTRA_REQUEST_CODE = "request_code";
	public static final String ERROR_MESSAGE = "err_msg";
	public static final String RECORDS = "records";

	public static final int STATUS_RUNNING = 1;
	public static final int STATUS_ERROR = 2;
	public static final int STATUS_FINISHED = 3;

	public String BASE_URL = "http://gdata.youtube.com/feeds/api/users/";

	private int queryCode;

	private final HttpConnector connector;
	private ChannelProcessor channelProcessor;

	public UpdateChannelService() {
		super(TAG);
		connector = HttpConnector.getInstance();
	}

	@Override
	public void onCreate() {
		super.onCreate();
		channelProcessor = new ChannelProcessor();
	}

	/**
	 * This method manages sends request to a server, parses response from it
	 * and updates database with new values.
	 */
	@Override
	protected void onHandleIntent(final Intent intent) {

		String final_url = null;
		String type = intent.getStringExtra(Config.TYPE);
		final_url = BASE_URL + type;

		final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_STATUS_RECEIVER);
		if (null != receiver)
			receiver.send(STATUS_RUNNING, null);

		queryCode = intent.getIntExtra(EXTRA_REQUEST_CODE, -1);
		final Bundle resultData = new Bundle();
		InputStream responseStream = null;

		try {
			switch (queryCode) {
			case Config.YTUBE:
				responseStream = connector.sendGETRequest(final_url);
				channelProcessor.processInternal(getContentResolver(), responseStream, type);
				if (type.equals(Config.arrayChannels[Config.arrayChannels.length - 1])) {
					receiver.send(STATUS_FINISHED, resultData);
				}
				break;
			default:
				break;
			}

		} catch (Exception ex) {
			Log.e(TAG, ex.getMessage(), ex);
			final Bundle errInfo = new Bundle();
			errInfo.putString(ERROR_MESSAGE, "No internet connection...");
			if (null != receiver)
				receiver.send(STATUS_ERROR, errInfo);
		}
	}
}
